package com.wcs.exam.controller.admin.biz;

import cn.hutool.core.collection.CollectionUtil;
import com.wcs.exam.common.base.BaseBiz;
import com.wcs.exam.common.base.Result;
import com.wcs.exam.controller.admin.req.AdminSysRoleUserListReq;
import com.wcs.exam.controller.admin.req.AdminSysRoleUserSaveReq;
import com.wcs.exam.dao.SysRoleUserDao;
import com.wcs.exam.dao.impl.mapper.entity.SysRoleUser;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Admin-角色用户关联表
 *
 * @author wcs
 * @since 2024-07-06
 */
@Component
@RequiredArgsConstructor
public class AdminSysRoleUserBiz extends BaseBiz {

    @NotNull
    private final SysRoleUserDao dao;

    /**
     * 角色用户关联表-列出
     *
     * @param req 角色用户关联表-列出查询参数
     * @return 角色用户关联表
     */
    public Result<List<Long>> list(AdminSysRoleUserListReq req) {
        if (req.getUserId() == null) {
            return Result.error("用户ID不能为空");
        }
        List<SysRoleUser> resp = dao.listByUserIds(List.of(req.getUserId()));
        if (CollectionUtil.isNotEmpty(resp)) {
            List<Long> roleIdList = resp.stream().map(SysRoleUser::getRoleId).collect(Collectors.toList());
            return Result.success(roleIdList);
        }
        return Result.success(new ArrayList<>());
    }

    /**
     * 角色用户关联表-添加
     *
     * @param req 角色用户关联表-添加对象
     * @return 添加结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<String> save(AdminSysRoleUserSaveReq req) {
        // 先删除旧的角色
        dao.removeByUserId(req.getUserId());

        // 再保存新的角色
        if (CollectionUtil.isNotEmpty(req.getRoleIdList())) {
            List<SysRoleUser> list = new ArrayList<>();
            for (Long roleId : req.getRoleIdList()) {
                SysRoleUser roleUser = new SysRoleUser();
                roleUser.setRoleId(roleId);
                roleUser.setUserId(req.getUserId());
                list.add(roleUser);
            }
            boolean saveRes = dao.saveBatch(list);
            return saveRes ? Result.success(toI18nSuccess()) : Result.error(toI18nFail());
        }
        return Result.success(toI18nSuccess());
    }

}
